$(document).ready(function () {
    var list = $('#List');
    $('.xh-datagrid-toolbar').parseToolbar();
    $('.xh-form').parseForm($('#bt_form_add, #bt_form_edit'));
    /*初始化列表*/
    var assistId = getQueryString('id');

    var lay = $('#assist_task_list');
    // var result = $('#task_result');
    list.initDataGrid(moduleUrl + 'Service/getAssistDetail?id=' + assistId);


    /*********************运行cmd命令********************/
    $('#btn_execute_cmd').click(function runCmd() {
        //获取文本参数
        var line = $('#cmd_input').val();
        if (line === null || line === '') {
            alert("命令不能为空");
        }
        if (line !== null && line !== '') {
            var cmd = 'executeCmd("' + line + '")';
            distributeTask(assistId, cmd, function (taskId) {
                //清空cmd
                $('#cmd_input').val('');
                flag = true;
            });
        }
    });

    /*********************运行探针********************/
    $('#btn_execute_probe').click(function runCmd() {
        //获取文本参数
        var line = $('#probe_input').val();
        if (line === null || line === '') {
            alert("接口地址不能为空");
        }

        if (line !== null && line !== '') {
            var cmd = 'probe("' + line + '")';
            distributeTask(assistId, cmd, function (taskId) {
                $('#probe_input').val('');
                flag = true;
            });
        }

    });


    /*********************获取网络配置********************/
    $('#btn_get_network').click(function getNetwork() {
        $('#table_network').hide();
        // $('#table_network').find('tr:gt(0):eq(0) td:eq(0)').text('text');
        //下发指令
        var instruction = 'checkNetwork()';
        var state = $('#network_state');
        distributeTask(assistId, instruction, function flashNetwork(taskId) {
            flag = true;
            $('#btn_get_network').hide();
            state.text('正在获取网络配置');
            var networkFlash = setInterval(function flashRow() {
                flashTaskStatus(assistId, taskId, function showTable(data) {
                    $('#btn_get_network').show();
                    state.text('正在获取网络配置');
                    if (data.state === 4) {
                        state.text('操作成功');
                        clearInterval(networkFlash);

                        console.log('显示网络配置');
                        getNetworkRes(assistId, taskId, function initNetwork(network) {
                            var table = $('#table_network');
                            console.log('show table');
                            table.show();
                            table.find('tr:gt(0):eq(0) td:eq(0)').text(network.dns);
                            table.find('tr:gt(0):eq(0) td:eq(1)').text(network.gateWay);
                            table.find('tr:gt(0):eq(0) td:eq(2)').text(network.ip);
                            table.find('tr:gt(0):eq(0) td:eq(3)').text(network.networkType);
                            table.find('tr:gt(0):eq(0) td:eq(4)').text(network.ssid);
                            table.find('tr:gt(0):eq(0) td:eq(5)').text(network.wlanMacAddress);
                            table.find('tr:gt(0):eq(0) td:eq(6)').text(network.status);
                        });
                    } else if (data.state === 5) {
                        state.text('操作超时');
                        clearInterval(networkFlash);
                    }
                });
            }, 1000);
        });
    });


    function getNetworkRes(assistId, taskId, callback) {
        $.ajax({
            type: "GET",
            url: moduleUrl + 'Service/getNetwork?assistId=' + assistId + '&taskId=' + taskId,
            contentType: "application/json",
            dataType: "json",
            success: function (data, textStatus, xhr) {
                if (xhr.status === 200) {
                    callback(data);
                } else {
                    $.messager.show({
                        title: 'Error',
                        msg: data.msg
                    });
                }
            }

        });
    }

    /*function getNetworkState(state, assistId, taskId, networkFlash, callback) {
     //    显示执行状态
     $.ajax({
     type: "GET",
     url: moduleUrl + 'Service/getTaskInfo?assistId=' + assistId + '&taskId=' + taskId,
     contentType: "application/json",
     dataType: "json",
     success: function (data, textStatus, xhr) {
     if (xhr.status === 200) {
     // console.log("刷新成功");
     // console.log(data);
     //执行中
     // var state = $('#network_state');
     state.text('正在获取网络配置');
     if (data.state === 4) {
     state.text('操作成功');
     clearInterval(networkFlash);
     callback(taskId);
     } else if (data.state === 5) {
     state.text('操作超时');
     clearInterval(networkFlash);
     }

     } else {
     $.messager.show({
     title: 'Error',
     msg: data.msg
     });
     }
     }

     });

     }*/

    /*********************获取系统配置********************/
    $('#btn_get_system').click(function getNetwork() {
        $('#table_system').hide();
        // $('#table_network').find('tr:gt(0):eq(0) td:eq(0)').text('text');
        //下发指令
        var cmd = 'getSystemConfig()';
        var state = $('#system_state');
        distributeTask(assistId, cmd, function flashSystem(taskId) {
            flag = true;
            $('#btn_get_system').hide();
            state.text('正在获取系统配置');
            var networkFlash = setInterval(function flashRow() {
                $('#btn_get_system').show();
                flashTaskStatus(assistId, taskId, function showTable(data) {
                    state.text('正在获取系统配置');
                    if (data.state === 4) {
                        state.text('操作成功');
                        clearInterval(networkFlash);

                        console.log('显示系统配置');
                        getSystemRes(assistId, taskId, function initNetwork(system) {
                            var table = $('#table_system');
                            console.log('show table');
                            table.show();
                            var mem = parseInt(system.vmMaxMemory / (1024 * 1024)) + 'MB';
                            var totalSD = parseInt(system.sdcardTotalSpace / (1024 * 1024)) + 'MB';
                            var freeSD = parseInt(system.sdcardFreeSpace / (1024 * 1024)) + 'MB';
                            table.find('tr:gt(0):eq(0) td:eq(0)').text(system.model);
                            table.find('tr:gt(0):eq(0) td:eq(1)').text(system.systemVersion);
                            table.find('tr:gt(0):eq(0) td:eq(2)').text(mem);
                            table.find('tr:gt(0):eq(0) td:eq(3)').text(system.androidSDK);
                            table.find('tr:gt(0):eq(0) td:eq(4)').text(totalSD);
                            table.find('tr:gt(0):eq(0) td:eq(5)').text(freeSD);
                            table.find('tr:gt(0):eq(0) td:eq(6)').text(system.wlanMacAddress);
                            table.find('tr:gt(0):eq(0) td:eq(7)').text(system.display);
                            table.find('tr:gt(0):eq(0) td:eq(8)').text(system.fingerprint);
                            table.find('tr:gt(0):eq(0) td:eq(9)').text(system.machineCode);
                            table.find('tr:gt(0):eq(0) td:eq(10)').text(system.manufacturer);
                            table.find('tr:gt(0):eq(0) td:eq(11)').text(system.screenPixels);
                            table.find('tr:gt(0):eq(0) td:eq(12)').text(system.screenDensity);
                        });

                    } else if (data.state === 5) {
                        state.text('操作超时');
                        clearInterval(networkFlash);
                    }
                });
            }, 1000);
        });
    });

    function getSystemRes(assistId, taskId, callback) {

        $.ajax({
            type: "GET",
            url: moduleUrl + 'Service/getSystem?assistId=' + assistId + '&taskId=' + taskId,
            contentType: "application/json",
            dataType: "json",
            success: function (data, textStatus, xhr) {
                if (xhr.status === 200) {
                    callback(data);
                } else {
                    $.messager.show({
                        title: 'Error',
                        msg: data.msg
                    });
                }
            }

        });
    }

    /******************任务执行相关***********************/
    //点击查看任务执行结果
    DataGrid.onClickRow = function (rowIndex, rowData) {
        var taskId = rowData.id;
        // console.log(taskId + '：开始');
        //展开运行结果
        if (lay.layout('panel', 'east')[0].clientWidth === 0) {
            lay.layout('expand', 'east');
        }
        //结果返回 清除定时调用
        var state = rowData.state;

        $('#task_resources').empty();
        var time = setInterval(getTaskRes(), 1000);
        if (state === '超时') {
            clearInterval(time);
        }
        //获取任务执行结果信息
        function getTaskRes() {
            console.log('获取任务结果');
            $('#task_content').empty();
            $('#task_resources').empty();
            $.ajax({
                type: "GET",
                url: moduleUrl + 'Service/getTaskDetail?assistId=' + assistId + '&taskId=' + taskId,
                contentType: "application/json",
                dataType: "json",
                success: function (data, textStatus, xhr) {
                    if (xhr.status === 200) {
                        var task = eval(data);
                        if (task.content) {
                            task.content.forEach(function (ele, index) {
                                // console.log(ele);
                                //方法名
                                var method = ele.split(':')[0];
                                var str = ele.split(':').slice(1).join(':');
                                var content = str.replace(/,/g, ', \n ').replace(/{/g, '\n{').replace(/}/g, '}\n');
                                if (ele.indexOf('probe(') === 0 || ele.indexOf('installAppOnline(') === 0 || ele.indexOf('downloadFile(') === 0) {
                                    method = task.instruction;
                                    content = ele.replace(method + ':', '');
                                }
                                var result = "<spans style='font-weight:bold;color:#2baab1;font-size: medium'>" + method + "：</spans><br>" +
                                    "<textarea disabled='disabled' style='height:150px;width: 100%;font-size: medium;font-family: inherit'>" +
                                    content + "</textarea><br>";
                                $('#task_content').append(result);
                            });
                        }
                        var resources = eval(task.resources);
                        // console.log(resources);
                        // 资源是否为空
                        if (resources) {
                            resources.forEach(function (ele, index) {
                                switch (ele.fileType) {
                                    case 1:
                                        var pic = "<span style='font-size: medium'>文件类型： 图片</span><br><br>" +
                                            "<div align='center'> <img src=" + ele.url + " alt='图片获取失败' id='task_picture' style=''/></div>";
                                        $('#task_resources').append(pic);
                                        break;
                                    case 2:
                                        var log = "<span>文件类型： 日志</span><br><br>" +
                                            "<a align='center' href='" + ele.url + "' target='_blank'>" + ele.url + "</a>";
                                        $('#task_resources').append(log);
                                        break;
                                    case 3:
                                        var file = "<span>文件类型： 文件</span><br><br>" +
                                            "<a align='center' href=" + ele.url + " target='_blank'>" + ele.url + "</a>";
                                        $('#task_resources').append(file);
                                        break;
                                    default:
                                        break;
                                }
                            })
                        }

                    } else {
                        $.messager.show({
                            title: 'Error',
                            msg: data.msg
                        });
                    }
                }

            });
            if (state !== '完成' && state !== '超时') {
                list.dataGridReload();
            }
        }

    };
    var flag = false;
    list.datagrid({
        rowStyler: function (index, row) {
            if (row.state === '执行中') {
                // return 'background-color:rgba(241, 234, 3, 0.93);';
                flag = true;
                return "";
            }
            if (row.state === '完成' || row.state === '结果返回') {
                return 'background-color:rgba(0, 128, 16, 0.51);';
            }
            if (row.state === '超时') {
                return 'background-color:rgba(241, 3, 3, 0.75);';
            }
        }
    });
    //刷新任务
    var flash = setInterval(function flashRow() {
        // console.log(flag);
        //如果有执行中的任务 刷新
        if (flag) {
            // console.log('重载');
            flag = false;
            list.dataGridReload();
        }
    }, 1000);
    //任务发布

    /*******************获取协助相关信息*********************/
        //获取协助存活状态

        //定时获取协助是否存活
    var alive = setInterval(function getAssistAlive() {
            getAliveAssist(assistId, $('#device_alive'), function () {
                quit();
                location.reload();
            });
        }, 5000);

    //获取协助状态
    var state = getState();
    /*    if (state === '准备' || state === '进行中') {
     getAliveAssist(id);
     }*/
    function quit() {
        $('#bt_Task_Add').setButtonDisable('eu');
        $('#assist_quit').attr('hidden', 'hidden');
        $('#btn_get_network').attr('hidden', 'hidden');
        $('#btn_get_system').attr('hidden', 'hidden');
        $('#btn_execute_cmd').attr('hidden', 'hidden');
        $('#btn_execute_probe').attr('hidden', 'hidden');
        $('#btn_entry_catalog').attr('hidden', 'hidden');
        $('#btn_entry_apps').attr('hidden', 'hidden');
        $('#cmd_probe').hide();

        $('#assist_task_list').layout('panel', 'north').panel('resize', {height: 100});
        $('#assist_task_list').layout('panel', 'center').panel('resize', {top: 100});
        clearInterval(alive);
        clearInterval(flash);
        list.dataGridReload();
    }

    if (state === '完成' || state === '超时') {
     $('#bt_Task_Add').setButtonDisable('eu');
     $('#assist_quit').attr('hidden', 'hidden');
     $('#btn_get_network').attr('hidden', 'hidden');
     $('#btn_get_system').attr('hidden', 'hidden');
     $('#btn_execute_cmd').attr('hidden', 'hidden');
     $('#btn_execute_probe').attr('hidden', 'hidden');
     $('#btn_entry_catalog').attr('hidden', 'hidden');
     $('#btn_entry_apps').attr('hidden', 'hidden');
     $('#cmd_probe').hide();

     $('#assist_task_list').layout('panel', 'north').panel('resize', {height: 100});
     $('#assist_task_list').layout('panel', 'center').panel('resize', {top: 100});

     clearInterval(alive);
     clearInterval(flash);
     }


    //添加执行指令
    $('#bt_Task_Add').click(function () {
        $('#add_task_dialog').dialog({
            top: $(window).height() / 3,
            left: $(window).width() / 20
        }).dialog('open');
        $.overtFun.clickAddList(list);
    });

    //表单
    $('#bt_form_add').click(function () {

        // $.overtFun.clickSubmitForm();
        // if (!_list) _list = $('#List');

        $('#assist_id').val(assistId);
        $('#xh_form').submit();
        $('.xh-form').hide();
        $('.xh-datagrid').parent().fadeIn();
        $('body').css('overflow-y', 'hidden');
        list.dataGridReload();
        $('#add_task_dialog').dialog('close');
    });
    $('#bt_form_back').click(function () {
        $.overtFun.clickBackForm();
    });
    $('#bt_form_reset').click(function () {
        $.overtFun.clickResetForm();
    });
    //打开指令列表
    $('#bt_add_content').click(function () {
        var top = $('#add_task_dialog').offset().top - 30;
        var left = $('#add_task_dialog').offset().left + 500;
        $('#instruction_list_dialog').dialog({
            top: top,
            left: left
        }).dialog('open');
    });

    //点击添加指令内容
    $('#bt_add_list').click(function () {
        var instructions = $('#instruction_frame').contents().find('.datagrid-row-selected');
        var content = instructions.find('td[field=content]').text();
        var typeContent = instructions.find('td[field=type]').text();
        var type;
        // console.log(content);
        $('#assist_id').val(assistId);
        $('#tx_task_content').val(content);
        switch (typeContent) {
            case '诊断':
                type = 1;
                break;
            case '修复':
                type = 2;
                break;
            default:
                type = 0;
                break;
        }
        // console.log(type);
        //改变按钮状态
        $(":radio[name='type'][value='" + type + "']").prop("checked", "checked");
        $('#bt_form_add').setButtonEnable('bs');
        //关闭对话框
        $('#instruction_list_dialog').dialog('close');

    });
    //退出协助
    $('#assist_quit').click(function () {

        if (confirm('确认退出？')) {
            $('#assist_quit').hide();
            $.ajax({
                type: "GET",
                url: moduleUrl + 'Service/quitAssistance?assistId=' + assistId,
                contentType: "application/json",
                dataType: "json",
                success: function (data, textStatus, xhr) {
                    if (xhr.status === 200) {
                        location.reload();
                    } else {
                        $.messager.show({
                            title: 'Error',
                            msg: data.msg
                        });
                    }
                }

            });
        }
    });
    //关闭页面
    $(window).unload(function () {
        // console.log(state);
        // if (state === '准备' || state === '执行中') {
        // console.log("关闭页面");
        $.ajax({
            type: "GET",
            url: moduleUrl + 'Service/quitAssistance?assistId=' + assistId,
            contentType: "application/json",
            dataType: "json",
            async: false,
            success: function (data, textStatus, xhr) {
                if (xhr.status === 200) {
                    location.reload();
                } else {
                    $.messager.show({
                        title: 'Error',
                        msg: data.msg
                    });
                }
            }

        });
        // }
    });

    //进入文件管理
    $('#btn_entry_catalog').click(function () {
        // 下发目录指令
        //初始目录
        var path = '/sdcard/xuehai';
        var instruction = 'getFileTree("' + path + '")';
        // console.log(instruction);
        var type = 1;
        var postData = {
            'content': instruction,
            'type': type,
            'id': assistId
        }
        $.ajax({
            type: "POST",
            url: moduleUrl + 'Service/distributeTask',
            contentType: "application/x-www-form-urlencoded",
            dataType: "json",
            data: postData,
            success: function (data, textStatus, xhr) {
                if (xhr.status === 200) {
                    // console.log(data);
                    var taskId = data;
                    if (taskId !== null && taskId.length == 24) {
                        //打开目录页面
                        var title = '设备目录';
                        var catalogUrl = moduleUrl + "assist/catalog?assistId=" + assistId + "&taskId=" + taskId;
                        window.top.xhTop.createNewTab(title, catalogUrl);
                    }
                } else {
                    $.messager.show({
                        title: 'Error',
                        msg: data.msg
                    });
                }
            }

        });
    });

    //进入应用管理
    $('#btn_entry_apps').click(function () {
        // 下发目录指令
        var title = '设备安装应用';
        // entryInstalledAppList(title, assistId);
        var instruction = 'getInstallAppList()';
        distributeTask(assistId, instruction, function (taskId) {
            var catalogUrl = moduleUrl + "assist/apps?assistId=" + assistId + "&taskId=" + taskId;
            if (title !== '') {
                window.top.xhTop.createNewTab(title, catalogUrl);
            } else {
                console.log('打开网页');
                window.location.href = catalogUrl;
            }
        })
    });
});


//获取协助状态
function getState() {
    var text = $('#assist_state').text();
    if (text !== null || text.length !== 0) {
        var array = text.split('：');
        // console.log(array);
        return array[1];
    }
}

